package com.lanou.web.controller;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.lanou.pojo.GeetInit;
import com.lanou.service.UserService;
import com.lanou.utils.GeetestLib;
import com.lanou.utils.ShiHuiResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Created by QuChao on 2018/12/4
 */
@RestController
@RequestMapping("/member")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private JedisPool jedisPool;

    @GetMapping("/checkLogin")
    public Map<String, Object> checkLogin(String token) {
        return userService.checkLoginStatus(token);
    }

    @GetMapping("/geetestInit")
    public Map<String, Object> geetesrInit(HttpServletRequest request) {

        GeetestLib gtSdk = new GeetestLib(GeetestLib.id, GeetestLib.key, GeetestLib.newfailback);

        String resStr = "{}";

        //自定义参数,可选择添加
        HashMap<String, String> param = new HashMap<String, String>();

        //进行验证预处理
        int gtServerStatus = gtSdk.preProcess(param);

        //将服务器状态设置到redis中
//        request.getSession().setAttribute(gtSdk.gtServerStatusSessionKey, gtServerStatus);
        String key = UUID.randomUUID().toString();
        Jedis jedis = jedisPool.getResource();
        jedis.set(key, gtServerStatus + "");
        jedis.expire(key, 360);
        jedis.close();

        resStr = gtSdk.getResponseStr();
        GeetInit geetInit = new Gson().fromJson(resStr, GeetInit.class);
        geetInit.setStatusKey(key);
        String json = new Gson().toJson(geetInit);
        Map map = JSON.parseObject(json, Map.class);
        Map<String, Object> map1 = new HashMap<>();
        map1.put("challenge", map.get("challenge"));
        map1.put("gt", map.get("gt"));
        map1.put("statusKey", map.get("statusKey"));
        map1.put("success", map.get("success"));
        return map1;
    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> map) {

        //极验验证
        GeetestLib gtSdk = new GeetestLib(GeetestLib.id, GeetestLib.key, GeetestLib.newfailback);

        String challenge = map.get("challenge");
        String validate = map.get("validate");
        String seccode = map.get("seccode");

        //从redis中获取gt-server状态
        //int gt_server_status_code = (Integer) request.getSession().getAttribute(gtSdk.gtServerStatusSessionKey);
        Jedis jedis = jedisPool.getResource();
        int gt_server_status_code = Integer.parseInt(jedis.get(map.get("statusKey")));

        //自定义参数,可选择添加
        HashMap<String, String> param = new HashMap<String, String>();

        int gtResult = 0;

        if (gt_server_status_code == 1) {
            //gt-server正常，向gt-server进行二次验证
            gtResult = gtSdk.enhencedValidateRequest(challenge, validate, seccode, param);
            System.out.println(gtResult);
        } else {
            // gt-server非正常情况下，进行failback模式验证
            System.out.println("failback:use your own server captcha validate");
            gtResult = gtSdk.failbackValidateRequest(challenge, validate, seccode);
            System.out.println(gtResult);
        }

        if (gtResult == 1) {
            // 验证成功
            Map<String, Object> login = userService.login(map);
            if (login != null) {
                return login;
            } else {
                return ShiHuiResult.error(400);
            }
        } else {
            // 验证失败
            return ShiHuiResult.error(400);
        }
    }

    @GetMapping("/member/loginOut")
    public Map<String, Object> logout(@RequestParam(defaultValue = "") String token) {
        boolean logout = userService.logout(token);
        return logout ? ShiHuiResult.ok() : ShiHuiResult.error(400);
    }


    @PostMapping("/member/register")
    public Map<String, Object> register(@RequestBody Map<String, String> map) {

        //极验验证
        GeetestLib gtSdk = new GeetestLib(GeetestLib.id, GeetestLib.key, GeetestLib.newfailback);

        String challenge = map.get("challenge");
        String validate = map.get("validate");
        String seccode = map.get("seccode");

        //从redis中获取gt-server状态
        //int gt_server_status_code = (Integer) request.getSession().getAttribute(gtSdk.gtServerStatusSessionKey);
        Jedis jedis = jedisPool.getResource();
        int gt_server_status_code = Integer.parseInt(jedis.get(map.get("statusKey")));
        jedis.close();

        //自定义参数,可选择添加
        HashMap<String, String> param = new HashMap<String, String>();

        int gtResult = 0;

        if (gt_server_status_code == 1) {
            //gt-server正常，向gt-server进行二次验证
            gtResult = gtSdk.enhencedValidateRequest(challenge, validate, seccode, param);
            System.out.println(gtResult);
        } else {
            // gt-server非正常情况下，进行failback模式验证
            System.out.println("failback:use your own server captcha validate");
            gtResult = gtSdk.failbackValidateRequest(challenge, validate, seccode);
            System.out.println(gtResult);
        }

        if (gtResult == 1) {
            // 验证成功
            boolean result = userService.register(map.get("userName"), map.get("userPwd"));
            return result ? ShiHuiResult.ok() : ShiHuiResult.error(400);
        } else {
            // 验证失败
            return ShiHuiResult.error(400);
        }
    }
}
